package cn.jiyun.consumer.controller;

import cn.jiyun.consumer.client.UserClient;
import cn.jiyun.consumer.pojo.User;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@RestController
@RequestMapping("/consumer")
@DefaultProperties(defaultFallback = "defaultFallback")
public class ConsumerController {

    @Autowired
    private RestTemplate restTemplate;

   /* @Autowired
    private DiscoveryClient discoveryClient;*/

   @Autowired
   private UserClient userClient;

    /**
     * 远程调用user-service，基于用户id查询用户信息
     */
    @GetMapping("/findById/{id}")
    //@HystrixCommand(fallbackMethod="fallbackMethod") //服务降级声明
    //@HystrixCommand //服务降级声明
    public User findById(@PathVariable("id") Long id){
        /*if(id==1){
            throw new RuntimeException("id参数错误");
        }*/
        //去注册中心发现服务
        //List<ServiceInstance> instanceList = discoveryClient.getInstances("user-service");
        //理论通过负载均衡算法完成服务实例调用，但是目前就一个服务
        //ServiceInstance instance = instanceList.get(0);
        //String url="http://user-service/user/findById/"+id;
        //String url="http://"+instance.getHost()+":"+instance.getPort()+"/user/findById/"+id;
        //String url="http://localhost:8081/user/findById/"+id;
        //User user = restTemplate.getForObject(url, User.class);
        User user = userClient.findById(id);
        return user;
    }

    //服务降级的方法
    public String fallbackMethod(Long id){
        return "执行了fallbackMethod服务降级方法。。。";
    }

    //针对整个controller默认的服务降级的方法
    public String defaultFallback(){
        return "执行了defaultFallback默认服务降级方法。。。";
    }


}
